package util.nlp;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Set;

import util.delicious.DmozEntryDescription;

import com.aliasi.chunk.Chunk;
import com.aliasi.chunk.Chunking;
import com.aliasi.dict.DictionaryEntry;
import com.aliasi.dict.ExactDictionaryChunker;
import com.aliasi.dict.TrieDictionary;
import com.aliasi.tokenizer.IndoEuropeanTokenizerFactory;
import com.aliasi.tokenizer.TokenizerFactory;

public class Dictionary {

	private TrieDictionary<String> dict = new TrieDictionary<String>();

	ExactDictionaryChunker chunker;

	Dictionary(LinkedList<DmozEntryDescription> entries) {

		for (int i = 0; i < entries.size(); i++) {
			DictionaryEntry<String> entry1 = new DictionaryEntry<String>(
					entries.get(i).url, entries.get(i).topic);
			dict.addEntry(entry1);
		}

		TokenizerFactory tokenizerFactory = IndoEuropeanTokenizerFactory.INSTANCE;

		chunker = new ExactDictionaryChunker(dict, tokenizerFactory);

	}

	public Dictionary(Hashtable<String, DmozEntryDescription> dmoz) {

		Enumeration<String> iter = dmoz.keys();

		while (iter.hasMoreElements()) {

			String key = iter.nextElement();

			DictionaryEntry<String> entry1 = new DictionaryEntry<String>(key,
					dmoz.get(key).topic);

		//	System.out.println(key + "\t" + dmoz.get(key).topic);
			dict.addEntry(entry1);

		}

		TokenizerFactory tokenizerFactory = IndoEuropeanTokenizerFactory.INSTANCE;

		chunker = new ExactDictionaryChunker(dict, tokenizerFactory);
	}

	public Dictionary(Hashtable<String, String> titles, int mode) {
		// TODO Auto-generated constructor stub
		Enumeration<String> iter = titles.keys();

		while (iter.hasMoreElements()) {

			String key = iter.nextElement();

			DictionaryEntry<String> entry1 = new DictionaryEntry<String>(key,
					titles.get(key));

		//	System.out.println(key + "\t" + dmoz.get(key).topic);
			dict.addEntry(entry1);

		}

		TokenizerFactory tokenizerFactory = IndoEuropeanTokenizerFactory.INSTANCE;

		chunker = new ExactDictionaryChunker(dict, tokenizerFactory);
		
		
		
		
		
	}

	public LinkedList<String> lookFor(String phrase) {

		Chunking chunking = chunker.chunk(phrase);
		CharSequence cs = chunking.charSequence();
		Set<Chunk> chunkSet = chunking.chunkSet();

		LinkedList<String> list = new LinkedList<String>();

		String current = "";

		for (Chunk chunk : chunkSet) {
			int start = chunk.start();
			int end = chunk.end();
			CharSequence str = cs.subSequence(start, end);

			current = str.toString();

			if (list.size() == 0) {
				list.add(current);

			} else {

				int j = list.size();
				
				boolean found =false;
				for (int i = 0; i < j; i++) {

					if (current.length() > list.get(i).length()) {

						list.add(i, current);
						i = j + 1;
						found = true;
					}

				}
				
				if(!found){
					list.addLast(current);
					
				}
				
				
			}
		}

		return list;
	}

}
